package cn.ncist.health_service_provider.service.impl;

import cn.ncist.health_interface.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Arrays;
import java.util.Date;

@Slf4j
@Service
@DubboService(interfaceClass = EmailService.class ,timeout = 50000)
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Override
    public void sendHtmlEmail(String email,Integer code) throws MessagingException {
        String validateCode = code.toString();
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        //设置邮件内容
        helper.setTo(email);
        helper.setSubject("华科健康验证码");
        helper.setFrom("2282527360@qq.com");
        helper.setSentDate(new Date());

        // 这里引入的是Template的Context
        Context context = new Context();
        //设置模板中的变量
        context.setVariable("verifyCode", Arrays.asList(validateCode.split("")));
        // 第一个参数为模板的名称
        String process = templateEngine.process("email.html", context); //这里不用写全路径
        // 第二个参数true表示这是一个html文本
        helper.setText(process,true);
        try {
            javaMailSender.send(mimeMessage);
            //将验证码存入redis缓存中
            redisTemplate.opsForValue().set(email +"validateCode",validateCode);
            log.info("发送成功！");
        } catch (MailException e) {
            e.printStackTrace();
            log.info("发送失败！");
        }
    }
}
